var express = require('express');
var router = express.Router();
const GoodModel = require('../models/goods');


router.get('/list',function(req,res,next){
	
	let page = parseInt(req.param("page"));
    let pageSize = parseInt(req.param("pageSize"));
    let skip = (page-1)*pageSize;
    let params = {};
    GoodModel.find(params).skip(skip).limit(pageSize).exec(function(err,doc){
//  	console.log(1111)
    	if(err){
            res.json({
                error:'1',
                msg:"错误"
            });
        }
    	//获取跨域图片
    	for(var i = 0; i< doc.length; i++){
    		doc[i].shopImg = '/images/'+ doc[i].shopImg;
    	}
        	res.json({
                error:'0',
                msg:'成功',
                result:{
                    count:doc.length,
                    list:doc
                }
            });
        
    })
    
    
})
//获取每个物品的详情
router.post('/shopmsg/:id',function(req,res){
//	console.log(req.params)
	var id = req.params.id
//	console.log(id)
	GoodModel.findById(id).exec(function(err,data){
//		console.log(data);
		if(err){
			return res.json({error:1,msg:'出错'});
		}
		if(!data){
			return res.json({error:1,msg:'商品不存在了'})
		}

    		data.shopImg = '/images/'+ data.shopImg;
   
		res.json({error:0,msg:"查找成功",data})
	})
})
//
router.post('/pingjiashop',function(req,res,next){

	var comment = req.body.comment;
	var user = req.cookies.name;
//	console.log(user)
	var name = req.body.shop.title;
	var now = new Date();
    req.body.time = {
        date:now,
        year:now.getFullYear(),
        month:now.getFullYear() + '-' + (now.getMonth() + 1 ),
        day:now.getFullYear() + '-' + (now.getMonth() + 1 ) + '-' + now.getDate(),
        minute:now.getFullYear() + '-' + (now.getMonth() + 1 ) + '-' + now.getDate() +
                ' ' + ( now.getHours() < 10 ? '0':'' ) + now.getHours() +
                ':' + ( now.getMinutes() < 10 ? '0' : '' ) + now.getMinutes()
    }

	
	GoodModel.find({"title":name}).exec(function(err,data){
		if(err){
			res.json({error:1,message:'系统错误'})
			}
   
		data.forEach(function(item){
			
			item.comments.push({
			content:comment,
			buyer:user,
			time:req.body.time
			})
			item.save();
		})
		res.json({error:0,message:'成功'});
	})
})
//获取卖家的全部商品
router.post('/sellshop/:author',function(req,res){
	var author = req.params.author;
	console.log(author);
	GoodModel.find({"author":author}).exec(function(err,data){
		console.log(data)
		if(err){
			return res.json({error:1,message:'系统错误'})
		}
		for(var i = 0; i < data.length; i++) {
			data[i].shopImg = '/images/' + data[i].shopImg
		}
		res.json({error:0,msg:"成功",result:{data}})
	})
})



module.exports = router;